#include "qdisplayfield.h"

QDisplayField::QDisplayField(QVBoxLayout* layout,QObject* parent)
   : QObject(parent),m_layout(layout)
{
	m_grid[EXP_CODE_PLP] 			= "Plp:";
	m_grid[EXP_VALUE] 				= "Valeur:";
	m_grid[EXP_MANUFACTURER] 		= "Fabricant:";
	m_grid[EXP_REF_MANUFACTURER] 	= "Ref.Fabricant:";
	m_grid[EXP_FOOTPRINT] 			= "Footprint:";
	m_pool = new QObjectPool<QEditableField>(m_grid.count());
}

QDisplayField::~QDisplayField()
{
	delete m_pool;
	m_pool = NULL;
}


void QDisplayField::setPartToDisplay(QEXPPart* part)
{
	clearLayout();
	if(part)
	{
		QEditableField* field;
		QHash<QString,QString>::iterator it;
		
		for(it=m_grid.begin();it!=m_grid.end();it++)
		{
			field = m_pool->acquire();
			if(field)
			{
				field->set(it.value(),part->get(it.key()));
				m_fields[it.key()] = field;
				connect(field,SIGNAL(hasChanged(const QString&)),this,SLOT(itemChanged(const QString&)));
				m_layout->addWidget(field);
			}
		}
	}
}

void QDisplayField::clearLayout()
{
	while(m_layout->count())
	{
		QWidget* widget = m_layout->itemAt(0)->widget();
		widget->disconnect();
		m_layout->removeWidget(widget);
		m_pool->release((QEditableField*)widget);
		m_fields.clear();
	}
}

void QDisplayField::itemChanged(const QString& change )
{
	emit partModified(getPartItems());
}

QStringList QDisplayField::getPartItems() const
{
	QStringList item;
	item << m_fields[EXP_CODE_PLP]->value();
	item << m_fields[EXP_VALUE]->value();
	item << m_fields[EXP_MANUFACTURER]->value();
	item << m_fields[EXP_REF_MANUFACTURER]->value();
	item << m_fields[EXP_FOOTPRINT]->value();
	return item;
}